<template>
  <div>
    <!--面包屑-->
    <el-breadcrumb separator="/" style="padding-left: 10px;padding-bottom: 10px;font-size: 12px">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <!--      <el-breadcrumb-item><a href="/">系统管理</a></el-breadcrumb-item>-->
      <el-breadcrumb-item>业务管理</el-breadcrumb-item>
      <el-breadcrumb-item>合同订单</el-breadcrumb-item>
    </el-breadcrumb>
    <!--用户列表卡片-->
    <el-card class="box-card">
      <el-form :inline="true" :model="queryMap" class="demo-form-inline" label-width="70px">
        <el-form-item label="客户" label-width="70px">
          <el-input clearable v-model="queryMap.cusName" placeholder="请输入客户姓名"></el-input>
        </el-form-item>
        <el-form-item label="签订日期" label-width="80px">
          <el-date-picker
            :clearable="false"
            v-model="range"
            type="datetimerange"
            :value-format="'yyyy-MM-dd HH:mm:ss'"
            :picker-options="pickerOptions"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            align="right">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="合同状态">
          <el-radio v-model="queryMap.staus" label="0">未完成</el-radio>
          <el-radio v-model="queryMap.staus" label="1">已完成</el-radio>
          <el-radio v-model="queryMap.staus" label>全部</el-radio>
        </el-form-item>
        <el-form-item label="员工" label-width="70px">
          <el-input clearable v-model="queryMap.username" placeholder="请输入员工姓名"></el-input>
        </el-form-item>
        <el-form-item label="合同编号" label-width="80px">
          <el-input clearable v-model="queryMap.conNum" placeholder="请输入合同编号"></el-input>
        </el-form-item>
        <el-form-item style="margin-left: 30px">
          <el-button icon="el-icon-refresh" @click="reset">重置</el-button>
          <el-button type="primary" icon="el-icon-search" @click="getCons">查询</el-button>
        </el-form-item>
      </el-form>
      <!--      表格内容显示区域-->
      <el-table
        v-loading="loading"
        :data="consList"
        border
        max-height="600"
        :header-cell-style="{'text-align':'center'}"
        :cell-style="{'text-align':'center'}"
        style="width: 100%;">
        <el-table-column
          fixed
          prop="id"
          label="#"
          width="50">
        </el-table-column>
        <el-table-column
          prop="conNum"
          :show-overflow-tooltip='true'
          fixed
          label="合同编号"
          width="130">
        </el-table-column>
        <el-table-column
          fixed
          prop="cusName"
          label="客户"
          width="120">
        </el-table-column>
        <el-table-column
          fixed
          prop="username"
          label="员工"
          width="120">
        </el-table-column>
        <el-table-column
          prop="date"
          label="签订日期"
          width="190">
        </el-table-column>
        <el-table-column
          label="完成日期"
          width="190">
          <template slot-scope="scope">
            {{scope.row.finishDate}}
            <el-tag size="middle" v-if="scope.row.staus===0">未开始</el-tag>
            <el-tag size="middle" type="warning" v-else-if="scope.row.staus===1">进行中</el-tag>
            <el-tag size="middle" type="info" v-else-if="scope.row.staus===-1">待审核</el-tag>
            <el-tag size="middle" type="success" v-else>已完成</el-tag>
          </template>
        </el-table-column>
        <el-table-column
          label="合同期限"
          width="190">
          <template slot-scope="scope">
            {{scope.row.deadline}}
            <el-tag size="middle" v-if="scope.row.staus!==2 && scope.row.deadDays>90" type="success">剩余{{scope.row.deadDays}}天</el-tag>
            <el-tag size="middle" v-else-if="scope.row.staus!==2 && scope.row.deadDays>60" type="warning">剩余{{scope.row.deadDays}}天</el-tag>
            <el-tag size="middle" v-else-if="scope.row.staus!==2 && scope.row.deadDays>0" type="danger">剩余{{scope.row.deadDays}}天</el-tag>
          </template>
        </el-table-column>
        <el-table-column
          prop="name"
          label="收货人"
          width="120">
        </el-table-column>
        <el-table-column
          prop="phone"
          label="联系方式"
          width="180">
        </el-table-column>
        <el-table-column
          prop="address"
          label="收货地址"
          :show-overflow-tooltip='true'
          width="180">
        </el-table-column>
        <el-table-column
          label="操作"
          width="180"
          fixed="right">
          <template slot-scope="scope">
            <el-button type="primary" size="mini" icon="el-icon-view" @click="detail(scope.row.id)"></el-button>
            <el-button type="success" size="mini" icon="el-icon-takeaway-box" :disabled="scope.row.staus==2" @click="addOutStock(scope.row.id)"></el-button>
            <el-button type="danger" size="mini" icon="el-icon-delete"></el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        style="padding-top:15px"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="current"
        :page-sizes="[10, 20, 30, 50]"
        :page-size="size"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total">
      </el-pagination>
      <el-dialog title="合同明细" :visible.sync="dialogVisible" @close="closeDetail" width="60%">
        <el-table max-height="300" border :data="detailTable" style="width: 100%"
                  :header-cell-style="{'text-align':'center'}"
                  :cell-style="{'text-align':'center'}">
          <el-table-column prop="name" label="名称" width="250px"></el-table-column>
          <el-table-column prop="model" label="规格" width="100px">
            <template slot-scope="scope">
              <el-tag size="small" effect="plain" type="success">
                {{ scope.row.model }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="orderNum" label="需求数量" width="120px"></el-table-column>
          <el-table-column label="完成进度" >
            <template slot-scope="scope">
              <span v-if="scope.row.staus===2">
                <el-tag size="middle" type="success" >已完成</el-tag>
              </span>
              <span v-else-if="scope.row.staus===1">
                <el-tag size="middle">已发货{{scope.row.finishNum}}{{scope.row.unit}},还剩{{scope.row.orderNum-scope.row.finishNum}}{{scope.row.unit}}未发货</el-tag>

              <el-tag size="middle" type="warning" style="margin-left: 10px">进行中</el-tag>
              </span>
              <span v-else>
              <el-tag size="middle" type="danger">未开始发货</el-tag>
              </span>



            </template>
          </el-table-column>
        </el-table>
        <!--              明细分页-->
        <el-pagination
          style="margin-top:20px;"
          background
          @current-change="handleDetailSizeChange"
          :current-page="this.pageNum"
          :page-size="5"
          layout="prev, pager, next,total"
          :total="this.detailTotal">
        </el-pagination>
      </el-dialog>

      <el-drawer
        :visible.sync="pdfVisible"
        direction='rtl'
        size="35%"
        :with-header="false"
        :before-close="handleClose"
        align="middle">
        <pdf
          :src="url"
          :page="currentPage"
          @num-pages="pageCount=$event"
          @page-loaded="currentPage=$event"
          @loaded="loadPdfHandler">
        </pdf>
        <el-button size="mini" type="text" @click="changePdfPage(0)" :disabled="currentPage==1">上一页</el-button>
        <el-tag size="mini" effect="plain" >{{currentPage}} / {{pageCount}}</el-tag>
        <el-button size="mini" type="text" @click="changePdfPage(1)" :disabled="currentPage==pageCount">下一页</el-button>


      </el-drawer>

      <el-dialog title="添加用户" @close="closeDialog" :visible.sync="addDialogVisible" width="50%;">
        <!-- 表单 -->
        <span>
          <el-form
            :model="addForm"
            :label-position="labelPosition"
            :rules="addFormRules"
            ref="addFormRef"
            label-width="80px"
          >
            <el-row>
              <el-col :span="10">
                <div class="grid-content bg-purple">
                  <el-form-item label="用户名" prop="username">
                    <el-input v-model="addForm.username"></el-input>
                  </el-form-item>
                </div>
              </el-col>
              <el-col :span="12">
                <div class="grid-content bg-purple-light">
                  <el-form-item label="部门" prop="departmentId">
                    <el-select v-model="addForm.departmentId" placeholder="请选择所属部门">
                      <el-option
                        v-for="department in departments"
                        :key="department.id"
                        :label="department.name"
                        :value="department.id"
                      ></el-option>
                    </el-select>
                  </el-form-item>
                </div>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="10">
                <div class="grid-content bg-purple">
                  <el-form-item label="昵称" prop="nickname">
                    <el-input v-model="addForm.nickname"></el-input>
                  </el-form-item>
                </div>
              </el-col>
              <el-col :span="12">
                <div class="grid-content bg-purple-light">
                  <el-form-item label="性别" prop="sex">
                    <el-radio-group v-model="addForm.sex">
                      <el-radio :label="1">帅哥</el-radio>
                      <el-radio :label="0">美女</el-radio>
                    </el-radio-group>
                  </el-form-item>
                </div>
              </el-col>
            </el-row>
            <el-form-item label="密码" prop="password">
              <el-input v-model="addForm.password"></el-input>
            </el-form-item>
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="addForm.email"></el-input>
            </el-form-item>
            <el-form-item label="手机" prop="phoneNumber">
              <el-input v-model="addForm.phoneNumber"></el-input>
            </el-form-item>
            <el-form-item prop="birth" label="生日">
              <el-col :span="11">
                <el-date-picker
                  type="date"
                  value-format="yyyy年MM月dd日"
                  placeholder="选择出生日期"
                  v-model="addForm.birth"
                  style="width: 100%;"
                ></el-date-picker>
              </el-col>
            </el-form-item>
          </el-form>
        </span>

        <span slot="footer" class="dialog-footer">
          <el-button @click="addDialogVisible = false">取 消</el-button>
          <el-button
            type="primary"
            @click="addUser"
            :loading="btnLoading"
            :disabled="btnDisabled"
          >确 定</el-button>
        </span>
      </el-dialog>

      <el-dialog title="修改用户" :visible.sync="editDialogVisible" width="50%" @close="editClose">
        <span>
          <el-form
            :model="editForm"
            :label-position="labelPosition"
            :rules="addFormRules"
            ref="editFormRef"
            label-width="80px"
          >
            <el-row>
              <el-col :span="10">
                <div class="grid-content bg-purple">
                  <el-form-item label="用户名" prop="username">
                    <el-input v-model="editForm.username" :disabled="true"></el-input>
                    <el-input
                      type="hidden"
                      v-model="editForm.id"
                      :disabled="true"
                      style="display:none;"
                    ></el-input>
                  </el-form-item>
                </div>
              </el-col>
              <el-col :span="12">
                <div class="grid-content bg-purple-light">
                  <el-form-item label="部门" prop="departmentId">
                    <el-select v-model="editForm.departmentId" placeholder="请选择所属部门">
                      <el-option
                        v-for="department in departments"
                        :key="department.id"
                        :label="department.name"
                        :value="department.id"
                      ></el-option>
                    </el-select>
                  </el-form-item>
                </div>
              </el-col>
            </el-row>

            <el-row>
              <el-col :span="10">
                <div class="grid-content bg-purple">
                  <el-form-item label="昵称" prop="nickname">
                    <el-input v-model="editForm.nickname"></el-input>
                  </el-form-item>
                </div>
              </el-col>
              <el-col :span="12">
                <div class="grid-content bg-purple-light">
                  <el-form-item label="性别" prop="sex">
                    <el-radio-group v-model="editForm.sex">
                      <el-radio :label="1">帅哥</el-radio>
                      <el-radio :label="0">美女</el-radio>
                    </el-radio-group>
                  </el-form-item>
                </div>
              </el-col>
            </el-row>

            <el-form-item label="邮箱" prop="email">
              <el-input v-model="editForm.email"></el-input>
            </el-form-item>
            <el-form-item label="联系方式" prop="phoneNumber">
              <el-input v-model="editForm.phone"></el-input>
            </el-form-item>
            <el-form-item prop="birth" label="生日">
              <el-col :span="11">
                <el-date-picker
                  type="date"
                  value-format="yyyy年MM月dd日"
                  placeholder="选择出生日期"
                  v-model="editForm.birth"
                  style="width: 100%;"
                ></el-date-picker>
              </el-col>
            </el-form-item>
          </el-form>
        </span>

        <span slot="footer" class="dialog-footer">
          <el-button @click="editDialogVisible = false">取 消</el-button>
          <el-button
            type="primary"
            @click="updateUser"
            :loading="btnLoading"
            :disabled="btnDisabled"
          >确 定</el-button>
        </span>
      </el-dialog>

    </el-card>
  </div>
</template>

<script>
import { getConList,getDetail,upload } from '../../api/con'
import pdf from 'vue-pdf'

export default {
  components:{
    pdf
  },
  name: 'OutStocks',
  data () {
    const checkEmail = (rule, value, callback) => {
      const mailReg = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(.[a-zA-Z0-9_-])+/
      if (!value) {
        return callback(new Error('邮箱不能为空'))
      }
      setTimeout(() => {
        if (mailReg.test(value)) {
          callback()
        } else {
          callback(new Error('请输入正确的邮箱格式'))
        }
      }, 100)
    }
    const checkPhone = (rule, value, callback) => {
      const phoneReg = /^1[34578]\d{9}$$/
      if (!value) {
        return callback(new Error('电话号码不能为空'))
      }
      setTimeout(() => {
        if (!Number.isInteger(+value)) {
          callback(new Error('请输入数字值'))
        } else {
          if (phoneReg.test(value)) {
            callback()
          } else {
            callback(new Error('电话号码格式不正确'))
          }
        }
      }, 100)
    }
    return {
      url:'',
      currentPage: 0, // pdf文件页码
      pageCount: 0, // pdf文件总页数
      pickerOptions: {
        shortcuts: [
          {
            text: '今天',
            onClick (picker) {
              const end = new Date()
              const start = new Date(new Date(new Date().toLocaleDateString()).getTime())
              picker.$emit('pick', [start, end])
            }
          },
          {
            text: '昨天',
            onClick (picker) {
              const end = new Date(new Date(new Date().toLocaleDateString()).getTime())
              const start = new Date(new Date(new Date().toLocaleDateString()).getTime())
              start.setTime(start.getTime() - 3600 * 1000 * 24)
              picker.$emit('pick', [start, end])
            }
          },
          {
            text: '最近一周',
            onClick (picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
              picker.$emit('pick', [start, end])
            }
          }, {
            text: '最近一个月',
            onClick (picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
              picker.$emit('pick', [start, end])
            }
          }, {}, {
            text: '最近两个月',
            onClick (picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 60)
              picker.$emit('pick', [start, end])
            }
          }, {
            text: '最近三个月',
            onClick (picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
              picker.$emit('pick', [start, end])
            }
          }]
      },
      current: 1,//当前页
      size: 10,
      total: 0,
      pageNum: 1,//明细页码
      loading: true,
      departments: [],
      range: [],
      detailId: undefined,
      detailTable: [],
      detailTotal: 0,
      btnLoading: false,
      pdfVisible:false,
      fileDialogVisible:false,
      addDialogVisible: false,
      editDialogVisible: false, //修改对话框
      btnDisabled: false,
      labelPosition: 'right', //lable对齐方式
      addFormRules: {
        username: [
          {
            required: true,
            message: '请输入用户名',
            trigger: 'blur'
          },
          {
            min: 3,
            max: 10,
            message: '长度在 3 到 10 个字符',
            trigger: 'blur'
          }
        ],
        password: [
          {
            required: true,
            message: '请输入密码',
            trigger: 'blur'
          },
          {
            min: 3,
            max: 12,
            message: '长度在 3 到 12 个字符',
            trigger: 'blur'
          }
        ],
        departmentId: [
          {
            required: true,
            message: '请选择部门',
            trigger: 'blur'
          }
        ],
        sex: [{
          required: true,
          message: '请选择性别',
          trigger: 'blur'
        }],
        birth: [{
          required: true,
          message: '请填写出生日期',
          trigger: 'blur'
        }],
        email: [{
          required: true,
          validator: checkEmail,
          trigger: 'blur'
        }],
        phoneNumber: [
          {
            required: true,
            message: '请输入联系方式',
            validator: checkPhone,
            trigger: 'blur'
          }
        ],
        nickname: [
          {
            required: true,
            message: '请输入昵称',
            trigger: 'blur'
          },
          {
            min: 5,
            max: 10,
            message: '长度在 5 到 10 个字符',
            trigger: 'blur'
          }
        ]
      },
      addForm: {
        username: '',
        nickname: '',
        password: '',
        email: '',
        phoneNumber: '',
        sex: '',
        birth: ''
      },
      editForm: {}, //更新表单
      queryMap: {
        username: '',
        staus: '',
        conNum: '',
        cusName: ''
      },
      consList: [],
      // 角色对话框的可见性
      dialogVisible: false,
      audit:false,
    }
  },
  created () {
    this.getCons()
    setTimeout(() => {
      this.loading = false
    }, 500)
  },
  methods: {
    reset () {
      this.queryMap = {
        username: '',
        staus: '',
        conNum: '',
        cusName: ''
      }
      this.queryMap.startTime = null
      this.queryMap.endTime = null
      this.range = []
    },
    // 每页条数改变
    handleSizeChange (val) {
      this.size = val
      this.getUsers()
      // console.log(`每页 ${val} 条`);
    },
    // 当前页码改变
    handleCurrentChange (val) {
      // console.log(`当前页: ${val}`);
      this.current = val
      this.getUsers()
    },
    pdfCurrentChange (val) {
      // console.log(`当前页: ${val}`);
      this.current = val
      this.currentPage=val
    },
    async getCons () {
      if (this.range != null && this.range.length === 1) {
        this.queryMap.startTime = this.range[0]
      } else if (this.range != null && this.range.length === 2) {
        this.queryMap.startTime = this.range[0]
        this.queryMap.endTime = this.range[1]
      }

      const res = await getConList(this.current, this.size, 3,this.queryMap)
      console.log(res)
      if (res.code !== 200) {
        return this.$message.error('获取合同列表失败:' + res.message)
      }
      this.consList = res.data.consList
      this.total = res.data.total
    },
    closeDialog () {
      this.$refs.addFormRef.clearValidate()
      this.addForm.birth = ''
      this.addForm = {}
    },
    async addUser () {
      this.$refs.addFormRef.validate(async valid => {
        if (!valid) {
          return
        } else {
          this.btnLoading = true
          this.btnDisabled = true
          const { data: res } = await this.$http.post('system/user/add', this.addForm)
          if (res.success) {
            this.$notify.success({
              title: '操作成功',
              message: '用户添加成功',
            })
            this.addForm = {}
            await this.getUsers()
            await this.getDepartments()
          } else {
            return this.$message.error('用户添加失败:' + res.data.errorMsg)
          }
          this.addDialogVisible = false
          this.btnLoading = false
          this.btnDisabled = false
        }
      })
    },
    /**
     * 修改用户信息
     */
    edit (row) {
      this.editForm = JSON.parse(JSON.stringify(row))
      this.editDialogVisible = true
    },
    /**
     * 查看合同订单明细
     */
    async detail (id) {
      this.detailId = id
      const res = await getDetail(id, this.pageNum)
      if (res.code !== 200) {
        this.$message.error('获取明细失败:' + res.message)
      } else {
        this.detailTable = res.data.goods
        this.detailTotal = res.data.total
        this.dialogVisible = true
      }
    },
    uploadSuccess () {
      this.getCons()
      this.$notify.success({
        title: '操作成功',
        message: '合同文件上传成功',
      })
    },
    uploadFailed () {
      this.$notify.error({
        title: '操作失败',
        message: '合同文件上传失败',
      })
    },
    openFile (file) {
      this.url = file
      this.pdfVisible=true
    },
    /**
     * 关闭明细
     */
    closeDetail () {
      this.pageNum = 1
    },
    /**
     *  改变明细页码
     */
    handleDetailSizeChange (newSize) {
      this.pageNum = newSize
      this.detail(this.detailId)
    },
    changePdfPage (val) {
      // console.log(val)
      if (val === 0 && this.currentPage > 1) {
        this.currentPage--
        // console.log(this.currentPage)
      }
      if (val === 1 && this.currentPage < this.pageCount) {
        this.currentPage++
        // console.log(this.currentPage)
      }
    },

    // pdf加载时
    loadPdfHandler (e) {
      this.currentPage = 1 // 加载的时候先加载第一页
    },
    handleClose(){
      this.currentPage = 1
      this.pdfVisible=false
    },
    addOutStock(id){
      this.$router.push({
        path: '/addOutStock',
        name: 'AddOutStock',
        params: {
          id: id,
        }
      })
    }
  }
}
</script>

<style scoped>

</style>
